package com.wf.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wf.domain.HousesInfo;
import com.wf.mapper.HousesInfoMapper;
import com.wf.service.HousesInfoService;
import com.wf.utils.AliOssUtil;
import com.wf.vo.PageQueryVO;
import com.wf.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * TODO
 *
 * @author chemin
 * @since 2024/9/2
 */
@Slf4j
@RestController
@RequestMapping("/admin")
public class HousesInfoController {
    @Autowired
    private HousesInfoService housesInfoService;
    @Autowired
    private HousesInfoMapper housesInfoInfoMapper;
    @Autowired
    AliOssUtil aliOssUtil;

    @GetMapping("/{housesId}")
    public Result findOne(@PathVariable("housesId") Integer housesId) {
        HousesInfo housesInfo = housesInfoService.getById(housesId);
        if (ObjectUtil.isNotEmpty(housesInfo)) {
            return new Result(0, "查询成功", housesInfo);
        }
        return new Result(1, "查询失败", housesInfo);

    }

    @GetMapping("/findPage")
    public Result findPage(PageQueryVO vo) {
        Page<HousesInfo> page = housesInfoService.findPage(vo);
        if (ObjectUtil.isNotEmpty(page)) {
            return new Result(0, "分页成功", page);
        }
        return new Result(0, "分页失败", page);
    }

    @GetMapping("/findAll")
    public Result findAll() {
        List<HousesInfo> housesInfoList = housesInfoService.list();
        if (CollectionUtil.isNotEmpty(housesInfoList)) {
            return new Result(0, "成功", housesInfoList);
        }
        return new Result(1, "失败", housesInfoList);
    }


    @PutMapping("/deleteHouse")
    public Result deleteHouse(Integer housesId) {
        boolean flag = false;
        int i = housesInfoInfoMapper.deleteById(housesId);
        if (i > 0) {
            flag = true;
        }
        return Result.success(flag);
    }

    @PostMapping("/upload")
    public Result upload(@RequestPart MultipartFile file) {

        // 获取上传文件的原始文件名
        String originalFilename = file.getOriginalFilename();

        // 校验文件是否为图片格式
        if (originalFilename == null || (!originalFilename.toLowerCase().endsWith(".jpg")
                && !originalFilename.toLowerCase().endsWith(".jpeg")
                && !originalFilename.toLowerCase().endsWith(".png"))) {
            return Result.failure("上传的文件不是图片格式！");
        }

        // 校验文件大小（限制 2MB）
        if (file.getSize() > 2 * 1024 * 1024) {
            return Result.failure("上传的图片大小不能超过 2MB！");
        }

        // 获取文件扩展名
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));

        // 生成随机文件名
        String format = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")) + "/";
        String objectName = format + UUID.randomUUID() + extension;

        try {
            // 调用aliOssUtil的upload方法上传文件，并获取上传后的文件路径
            String filePath = aliOssUtil.upload(file.getBytes(), objectName);

            // 返回成功的结果，包含文件路径
            return Result.success(filePath);
        } catch (IOException e) {
            // 如果发生IO异常，记录错误日志
            log.error("上传图片失败：", e);
            return Result.failure("图片上传失败");
        }
    }
}
